const express = require('express');
const path = require('path');
// const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');

const { formatTime, formatDate } = require('./util/tool/date');

let app = express();

const users_router = require('./routes/user');
const punchcard_router = require('./routes/punchcard');
const school_router = require('./routes/school');
const task_router = require('./routes/task');
const question_router = require('./routes/question');
const book_router = require('./routes/book');
const word_router = require('./routes/word');
const file_router = require('./routes/file');
const focuscard_router = require('./routes/focuscard');
const course_router = require('./routes/course');
const circle_router = require('./routes/circle');

// 输出所有请求的日志
app.use(function (req, res, next) {
    // 记录请求到达服务端的时间戳
    req.time = new Date();
    req.formatTime = formatTime(req.time);
    req.formatDate = formatDate(req.time);
    // 输出请求的日志 - 如果使用了反向代理 此处的地址可能不是客户端的 需要修改
    console.log(`${req.connection.remoteAddress} | ${req.time} | ${req.originalUrl} | `);
    next();
});

// 设置允许跨域请求
app.use(function (req, res, next) {
    // 添加允许跨域的请求头
    // 设置允许跨域的源为所有源
    res.setHeader('Access-Control-Allow-Origin', '*');
    // 设置允许的HTTP方法为所有方法
    res.setHeader('Access-Control-Allow-Methods', '*');
    // 设置允许的请求头为所有头
    res.setHeader('Access-Control-Allow-Headers', '*');
    // 解决预检请求
    if (req.method === 'OPTIONS') {
        res.sendStatus(200);
        return;
    }
    // 进行下一个路由的调用
    next();
});

// 设置http请求报文的长度限制为 15M
app.use(bodyParser.json({limit: '15mb'}));
app.use(bodyParser.urlencoded({limit: '15mb', extended: true}));

// 服务端解析json数据的中间件
app.use(express.json());
// 服务端解析GET请求参数的中间件
app.use(express.urlencoded({ extended: false }));

// 保证 req.body 一定是一个对象
app.use(function (req, res, next) {
    req.body = req.body || {};
    next();
});

// 服务端解析cookie的中间件（暂时不使用）
// app.use(cookieParser());

// 挂载静态资源
app.use(express.static(path.join(__dirname, 'public')));

// 动态路由
// 此处的引入其实可以写个本地目录的检测即可
app.use('/user', users_router);
app.use('/punchcard', punchcard_router);
app.use('/school', school_router);
app.use('/task', task_router);
app.use('/question', question_router);
app.use('/book', book_router);
app.use('/word', word_router);
app.use('/file', file_router);
app.use('/focuscard', focuscard_router);
app.use('/course', course_router);
app.use('/circle', circle_router);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    // res.send('404 Not Found');
    res.status(404);
    res.statusMessage = '404 not found';
    res.sendFile(path.join(__dirname, '/views/error.html'))
});

// app对象暴露
module.exports = app;
